<template>
  <div class="material-inventory">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>面料库存管理</span>
          <el-button type="primary" @click="handleAdd">新增面料</el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="面料编号">
          <el-input v-model="searchForm.materialCode" placeholder="请输入面料编号" clearable />
        </el-form-item>
        <el-form-item label="面料名称">
          <el-input v-model="searchForm.materialName" placeholder="请输入面料名称" clearable />
        </el-form-item>
        <el-form-item label="面料类型" style="width: 230px;">
          <el-select v-model="searchForm.materialType" placeholder="请选择面料类型" clearable>
            <el-option label="棉" value="棉" />
            <el-option label="麻" value="麻" />
            <el-option label="丝" value="丝" />
            <el-option label="毛" value="毛" />
            <el-option label="化纤" value="化纤" />
          </el-select>
        </el-form-item>
        <el-form-item label="颜色">
          <el-input v-model="searchForm.color" placeholder="请输入颜色" clearable />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="searchForm.supplier" placeholder="请输入供应商" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="materialList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="materialCode" label="面料编号" width="120" />
        <el-table-column prop="materialName" label="面料名称" width="150" />
        <el-table-column prop="materialType" label="面料类型" width="100" />
        <el-table-column prop="color" label="颜色" width="100" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="quantity" label="库存数量" width="100" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="supplier" label="供应商" width="150" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 新增/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增面料' : '编辑面料'"
        width="600px"
      >
        <el-form
          ref="materialFormRef"
          :model="materialForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="面料编号" prop="materialCode">
            <el-input v-model="materialForm.materialCode" placeholder="请输入面料编号" />
          </el-form-item>
          <el-form-item label="面料名称" prop="materialName">
            <el-input v-model="materialForm.materialName" placeholder="请输入面料名称" />
          </el-form-item>
          <el-form-item label="面料类型" prop="materialType">
            <el-select v-model="materialForm.materialType" placeholder="请选择面料类型">
              <el-option label="棉" value="棉" />
              <el-option label="麻" value="麻" />
              <el-option label="丝" value="丝" />
              <el-option label="毛" value="毛" />
              <el-option label="化纤" value="化纤" />
            </el-select>
          </el-form-item>
          <el-form-item label="颜色" prop="color">
            <el-input v-model="materialForm.color" placeholder="请输入颜色" />
          </el-form-item>
          <el-form-item label="规格" prop="specification">
            <el-input v-model="materialForm.specification" placeholder="请输入规格" />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="materialForm.unit" placeholder="请输入单位" />
          </el-form-item>
          <el-form-item label="库存数量" prop="quantity">
            <el-input-number v-model="materialForm.quantity" :min="0" />
          </el-form-item>
          <el-form-item label="单价" prop="price">
            <el-input-number v-model="materialForm.price" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="供应商" prop="supplier">
            <el-input v-model="materialForm.supplier" placeholder="请输入供应商" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="materialForm.remark"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'MaterialInventory',
  setup() {
    // 列表数据
    const loading = ref(false)
    const materialList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 搜索表单
    const searchForm = reactive({
      materialCode: '',
      materialName: '',
      materialType: '',
      color: '',
      supplier: ''
    })
    
    // 新增/编辑表单
    const materialFormRef = ref(null)
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const materialForm = reactive({
      id: '',
      materialCode: '',
      materialName: '',
      materialType: '',
      color: '',
      specification: '',
      unit: '',
      quantity: 0,
      price: 0,
      supplier: '',
      remark: ''
    })
    
    // 表单校验规则
    const rules = {
      materialCode: [
        { required: true, message: '请输入面料编号', trigger: 'blur' }
      ],
      materialName: [
        { required: true, message: '请输入面料名称', trigger: 'blur' }
      ],
      materialType: [
        { required: true, message: '请选择面料类型', trigger: 'change' }
      ],
      unit: [
        { required: true, message: '请输入单位', trigger: 'blur' }
      ],
      quantity: [
        { required: true, message: '请输入库存数量', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入单价', trigger: 'blur' }
      ]
    }
    
    // 获取面料列表
    const getMaterialList = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          ...searchForm
        }
        const res = await request.get('/api/admin/material-inventory', { params })
        materialList.value = res.data.content
        total.value = res.data.totalElements
      } catch (error) {
        console.error('获取面料列表失败:', error)
        ElMessage.error('获取面料列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      getMaterialList()
    }
    
    // 重置搜索
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      handleSearch()
    }
    
    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      getMaterialList()
    }
    
    // 当前页改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      getMaterialList()
    }
    
    // 新增面料
    const handleAdd = () => {
      dialogType.value = 'add'
      dialogVisible.value = true
      Object.keys(materialForm).forEach(key => {
        materialForm[key] = key === 'quantity' || key === 'price' ? 0 : ''
      })
    }
    
    // 编辑面料
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      dialogVisible.value = true
      Object.keys(materialForm).forEach(key => {
        materialForm[key] = row[key]
      })
    }
    
    // 删除面料
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确定要删除该面料吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await request.delete(`/api/admin/material-inventory/${row.id}`)
          ElMessage.success('删除成功')
          getMaterialList()
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      })
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!materialFormRef.value) return
      
      await materialFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogType.value === 'add') {
              await request.post('/api/admin/material-inventory', materialForm)
              ElMessage.success('添加成功')
            } else {
              await request.put(`/api/admin/material-inventory/${materialForm.id}`, materialForm)
              ElMessage.success('更新成功')
            }
            dialogVisible.value = false
            getMaterialList()
          } catch (error) {
            console.error('操作失败:', error)
            ElMessage.error('操作失败')
          }
        }
      })
    }
    
    onMounted(() => {
      getMaterialList()
    })
    
    return {
      loading,
      materialList,
      currentPage,
      pageSize,
      total,
      searchForm,
      materialFormRef,
      dialogVisible,
      dialogType,
      materialForm,
      rules,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.material-inventory {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 